package licode.unisop.client.feign.impl;

import licode.unisop.client.api.auth.SopUserAuthQuery;
import licode.unisop.client.info.SopRealmIdIn;
import licode.unisop.client.info.SopTokenInfo;
import licode.unisop.client.utils.SopAuthConst;
import licode.unisop.client.utils.SopException;
import licode.unisop.client.visit.UniClientTool;
import licode.unisop.client.visit.UserAuthQueryVisit;
import licode.unisop.client.vo.SopAuthBrief;
import licode.unisop.client.vo.SopAuthUser;
import licode.unisop.client.vo.SopCredential;
import licode.unisop.client.vo.SopUserBrief;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author licode
 */
@Component
public class UserAuthQueryVisitFeignImpl implements UserAuthQueryVisit {
    @Resource
    private HttpServletRequest request;

    @Resource
    private UniClientTool uniClientTool;

    @Resource
    private SopUserAuthQuery sopUserAuthQuery;

    private SopTokenInfo getAuthToken(SopRealmIdIn idIn) {
        return uniClientTool.getAuthToken(request, idIn);
    }

    public SopAuthBrief getTokenInfo(SopRealmIdIn idIn, boolean noThrow) {
        SopTokenInfo tokenInfo = getAuthToken(idIn);
        SopAuthBrief brief = sopUserAuthQuery.getAuthBrief(tokenInfo);
        if (null == brief && noThrow) {
            throw new SopException(SopAuthConst.USER_NOT_LOGIN, SopAuthConst.USER_NOT_LOGIN_MSG);
        }
        return brief;
    }

    public SopAuthUser getAuthInfo(SopRealmIdIn idIn) {
        return sopUserAuthQuery.getAuthUserInfo(getAuthToken(idIn));
    }

    public SopUserBrief getAuthUser(SopRealmIdIn idIn) {
        return sopUserAuthQuery.getUserInfo(getAuthToken(idIn));
    }

    public SopCredential getAuthCred(SopRealmIdIn idIn) {
        return sopUserAuthQuery.getCredential(getAuthToken(idIn));
    }

    public Map<String, Object> getUserAssets(SopRealmIdIn idIn) {
        SopTokenInfo tokenInfo = getAuthToken(idIn);
        return sopUserAuthQuery.getUserAssets(tokenInfo);
    }

    public boolean tokenValid(SopTokenInfo tokenInfo) {
        return sopUserAuthQuery.tokenValid(tokenInfo);
    }
}
